package com.lili.userservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lili.comnonbase.exception.BusinessException;
import com.lili.userservice.entity.TbUser;
import com.lili.userservice.service.TbUserService;
import com.lili.userservice.vo.TbUserVo;
import com.lili.utilscommon.pwdmd5.MD5utils;
import com.lili.utilscommon.response.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author lili
 * @since 2020-07-20
 */
@Api(value = "用户管理")
@RestController
@RequestMapping("/userservice/tb-user")
@CrossOrigin
public class TbUserController {

    @Autowired
    private TbUserService tbUserService;

    /**
     * 查所有
     *
     * @return
     */
    @ApiOperation(value = "查询所有用户")
    @GetMapping("/users")
    public Result users() {

        List<TbUser> users = tbUserService.list(null);
        return Result.ok().data("users", users);
    }

    /**
     * 逻辑删除
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "逻辑删除用户")
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") Integer id) {
        boolean delete = tbUserService.removeById(id);
        if (delete) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }


    @ApiOperation(value = "分页查询用户信息")
    @GetMapping("/{current}/{size}")
    public Result userpage(@PathVariable("current")Integer current,@PathVariable("size") Integer size) {
        Page<TbUser> page = new Page<>(current,size);
        Page<TbUser> userPage = tbUserService.page(page);
        long total = userPage.getTotal();
        List<TbUser> records = userPage.getRecords();
        return Result.ok().data("total",total).data("records",records);
    }

    @ApiOperation(value = "根据条件分页查询")
    @PostMapping("/userPageByCon/{current}/{size}")
    public Result userPageByCondition(@PathVariable("current")Integer current, @PathVariable("size") Integer size,@RequestBody(required = false) TbUserVo tbUserVo){
        Page<TbUser>page=new Page<>(current,size);
        QueryWrapper<TbUser> queryWrapper = getWrapper(tbUserVo);
        Page<TbUser>userPage = tbUserService.page(page,queryWrapper);
        long total = userPage.getTotal();
        List<TbUser> records = userPage.getRecords();
        return Result.ok().data("total",total).data("records",records);
    }

    /**
     * 传入的肯定是一个对象 json 对象
     * @param tbUser
     * @return
     */
    @ApiOperation(value = "添加用户信息")
    @PostMapping("addUser")
    public Result addUser(@RequestBody TbUser tbUser){
        tbUser.setStatus(1);
        tbUser.setSalt(UUID.randomUUID().toString().substring(0,32));
        tbUser.setType(1);
        tbUser.setAvatar("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1595328309181&di=19ccadbe5c288d950a330d1ee788b975&imgtype=0&src=http%3A%2F%2Fpic1.win4000.com%2Fpic%2F2%2F41%2Fa0b1882426.jpg");
        tbUser.setPassword(MD5utils.md5Encrtytion(tbUser.getPassword(),tbUser.getSalt()));
        boolean user = tbUserService.save(tbUser);
        if (user){
            return Result.ok();
        }else{
            return Result.error();
        }
    }

    @ApiOperation(value = "根据Id用户进行查询")
    @GetMapping("findById/{id}")
    public Result findById(@PathVariable("id") Long id){
        TbUser tbUser = tbUserService.getById(id);
        if (StringUtils.isEmpty(tbUser)){
        /*用户不存在 业务异常*/
        throw new BusinessException(20001,"用户不存在");
        }
    return Result.ok().data("tbUser",tbUser);
    }

    /**
     * 将查询条件进行封装
     * @param tbUserVo
     * @return
     */
    public QueryWrapper<TbUser> getWrapper(TbUserVo tbUserVo){
        QueryWrapper<TbUser> queryWrapper =new QueryWrapper<TbUser>();
        if (!StringUtils.isEmpty(tbUserVo.getDepartmentId())){
            queryWrapper.eq("department_id",tbUserVo.getDepartmentId());
        }
        if (!StringUtils.isEmpty(tbUserVo.getUsername())){
            System.out.println("1qweqw");
            queryWrapper.like("username",tbUserVo.getUsername());
        }
        if (!StringUtils.isEmpty(tbUserVo.getEmail())){
            queryWrapper.like("email",tbUserVo.getEmail());
        }
        if (!StringUtils.isEmpty(tbUserVo.getSex())){
            queryWrapper.eq("sex",tbUserVo.getSex());
        }
        if (!StringUtils.isEmpty(tbUserVo.getNickname())){
            queryWrapper.like("nickname",tbUserVo.getNickname());
        }
        return queryWrapper;
    }

    @ApiOperation(value = "查询用户信息和部门")
    @PostMapping("/userAndDeptPageCon/{current}/{size}")
    public Result userAndDeptPageCon(@PathVariable("current") Integer current, @PathVariable Integer size, @RequestBody(required = false) TbUserVo tbUserVO) {
        Page<TbUser> page = new Page<>(current, size);
        System.out.println(tbUserVO);
        QueryWrapper<TbUser> queryWrapper = this.getWrapper(tbUserVO);
        Page<TbUser> userPage = tbUserService.findUserPage(page, queryWrapper);
        return Result.ok().data("total", userPage.getTotal()).data("records", userPage.getRecords());
    }

    @ApiOperation(value = "使用mp方式查询用户信息和部门")
    @PostMapping("/findUserPage/{current}/{size}")
    public Result findUserPage(@PathVariable("current") Integer current, @PathVariable("size") Integer size, @RequestBody(required = false) TbUserVo tbUserVO) {
        Page<TbUser> page = new Page<>(current, size);
        //昨天提取的代码,封装了查询条件
        QueryWrapper<TbUser> wrapper = getWrapper(tbUserVO);
        IPage<TbUser> userPage = tbUserService.findUserPage(page, wrapper);
        long size1 = userPage.getSize();
        System.out.println(size1);
        return Result.ok().data("total",userPage.getTotal()).data("records",userPage.getRecords()).data("sizes",userPage.getSize());
    }

    @ApiOperation(value = "导出用户信息")
    @PostMapping (value = "/export")
    public void exportUserInfoExcel(HttpServletResponse response,@RequestBody(required = false) TbUserVo tbUserVO)throws IOException {
        QueryWrapper<TbUser> wrapper = getWrapper(tbUserVO);
        List<TbUser> tbUsers = tbUserService.list(wrapper);
        tbUserService.exprotUserInfoExcel(response,tbUsers);
    }

    @ApiOperation(value = "导入用户信息")
    @RequestMapping(value = "/import",method = {RequestMethod.GET,RequestMethod.POST})
    public String importUserInfoExcel(@RequestParam("File")MultipartFile file)throws IOException {
        tbUserService.impeotUserInfoExcel(file);
        return "success";
    }

    @ApiOperation(value = "注销登录")
    @PostMapping("/logout")
    public Result logout(){
        return Result.ok();
    }
}

